<?php

declare(strict_types=1);

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Library\Common;
use App\Model\FlyShopAd;
use App\Model\FlyTopic;
use App\Model\Moment;
use App\Model\MomentsProfile;
use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Rule;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * Class MomentService
 * @package App\Service
 */
class MomentService extends BaseService
{

    const STATUS_WAIT_CHECK = 0;
    const STATUS_CHECKED = 1;
    const STATUS_REFUSE = 2;// 被驳回

    const SHOW_UP = 1;// 上架
    const SHOW_DOWN = 0;// 下架

    const LEGAL = 0;// 合法
    const ILLEGAL = 1;// 违规

    const PROFILE_ARTICLE_IMG = 1;
    const PROFILE_PRODUCT = 2;

    const MOMENT_FROM_DR = 2; // 达人圈动态
    const MOMENT_FROM_SHOP = 1;// 商家动态

    /**
     * @Inject
     * @var MomentsApplyService
     */
    private $momentApply;

    /**
     * @Inject
     * @var MomentsReviewService
     */
    private $reviews;

    /**
     * @Inject
     * @var ProductService
     */
    private $product;

    /**
     * @Inject
     * @var FileinfoService
     */
    private $fileinfo;

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * @var ValidatorFactoryInterface
     */
    private $validate;

    /**
     * @Inject
     * @var FlyShopService
     */
    private $shop;

    /**
     * MomentService constructor.
     * @param RequestInterface $request
     * @param ValidatorFactoryInterface $validatorFactory
     */
    public function __construct(RequestInterface $request, ValidatorFactoryInterface $validatorFactory)
    {
        $this->request = $request;
        $this->validate = $validatorFactory;
    }

    /**
     * 验证返回动态参数
     * @param int $user_id
     * @param int|null $moments_id
     * @param int 动态类型：1商家动态 2达人圈动态
     * @return array
     */
    public function verify(int $user_id, $moments_id = null, $moment_from = self::MOMENT_FROM_SHOP): array
    {
        $inputs_field = ['type', 'act', 'video_file', 'video_desc', 'article_title', 'article', 'article_images', 'moment_products', 'topic_id'];
        // 达人圈-话题ID
        if ($moment_from == self::MOMENT_FROM_DR) {
            $inputs_field[] = "topic_id";
        }
        $data = $this->request->inputs($inputs_field);
        // 参数过滤
        $my_shop = $this->shop->getMyShop($user_id);
        if ($moment_from == self::MOMENT_FROM_SHOP && empty($my_shop)) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '获取店铺信息失败');
        }

        // 审核中-取消发布  上架-下架|编辑  下架-上架|编辑 违规-编辑
        $res = $this->validate->make($data, [
            'type' => Rule::in([1, 2]),
            'video_desc' => [
                Rule::requiredIf($data['type'] == 1),
                'max:255',
            ],
            'video_file' => [
                'integer',
                Rule::requiredIf(function () use ($data) {
                    // 发布视频
                    return $data['type'] == 1;
                })
            ],
            'article_title' => [
                'max:40',
                Rule::requiredIf(function () use ($data) {
                    return $data['type'] == 2;
                })
            ],
            'article' => [
                'max:400',
                Rule::requiredIf(function () use ($data) {
                    return $data['type'] == 2;
                })
            ],
            'article_images' => [
                'array',
                Rule::requiredIf(function () use ($data) {
                    return $data['type'] == 2;
                })
            ],
            'moment_products' => [
                'nullable',
                'required',
                'array'
            ],
            'act' => Rule::in([0, 1]),// 保存并提交：1提交上架审核 或 0仅保存草稿
        ]);
        if ($res->fails()) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, $res->errors()->first());
        }

        // 达人圈话题验证
        if ($moment_from == self::MOMENT_FROM_DR) {
            if (empty($data['topic_id'])) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '未选择话题');
            }
            if (!make(FlyTopic::class)->where('id', '=', $data['topic_id'])->exists()) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '话题不存在');
            }
        }

        // 修改动态：1下架并修改 2后台审核违规并修改
        if (!empty($moments_id)) {
            $moment = $this->getModelInstance()->where('user_id', '=', $user_id)->find($moments_id);
            // 上架提交审核状态不能编辑（先下架才能编辑）
            if (empty($moment) || $moment->type != $data['type'] || $moment->delete_time > 0) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '动态不存在');
            }
        }

        // 动态类型（视频、文章判断）
        $tmp_files = [];
        if ($data['type'] == 1) {
            $files = $this->fileinfo->getFileinfo([$data['video_file']]);
            // 验证视频文件
            if (empty($files) || $files[0]['user_id'] != $user_id || $files[0]['mimetype'] != 'mp4') {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '无效的视频文件');
            }
            $tmp_files['fileinfo_id'] = $files[0]['fileinfo_id'];
            $tmp_files['url'] = $files[0]['url'];
        } else {
            $files = $this->fileinfo->getFileinfo($data['article_images']);
            if (!empty($data['article_images']) && empty($files) || count($data['article_images']) != count($files)) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '图片无效');
            }
            foreach ($files as $file) {
                $tmp_files[] = [
                    'fileinfo_id' => $file['fileinfo_id'],
                    'url' => $file['url']
                ];
                if ($file['user_id'] != $user_id) {
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '无效的图片');
                }
            }
        }

        $return = [
            'id' => $moments_id,
            'shop_id' => $my_shop['id'] ?? 0,
            'user_id' => $user_id,
            'type' => $data['type'],
            'video_desc' => $data['video_desc'] ?? "",
            'act' => $data['act'] ?? 0,// 0 草稿 1发布提交审核
            'video_file' => $data['video_file'] ?: 0,
            'article_title' => $data['article_title'] ?? "",
            'article' => $data['article'] ?? "",
            'is_show' => $data['act'] ?? 0,
            'topic_id' => $data['topic_id'] ?? 0,
            'industry_id' => [], // 行业信息分类
        ];
        if (!empty($data['moment_products'])) {
            $products = $this->product->getProductById($data['moment_products']);
            if (count($products) != count($data['moment_products'])) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '存在无效商品');
            }
            $tmp_products = [];
            foreach ($products as $product) {
                // 商家动态、商品验证
                if (($moment_from == self::MOMENT_FROM_SHOP && $product['shop_id'] != $my_shop['id']) || empty($product['shop_min_sku']) || empty($product['main_pic'])) {
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '商品无效');
                }
                if ($moment_from == self::MOMENT_FROM_DR) {
                    // 判断是否发布商品为推广商品
                    $ad_profiles = make(FlyShopAd::class)
                        ->whereNull('deleted_at')
                        ->where('product_id', '=', $product['id'])
                        ->first();
                    if (empty($ad_profiles)) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '推广商品无效');
                    }
                    if ($ad_profiles->status == 2) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '商品已停止推广');
                    }
                }

                $tmp_products[] = [
                    'product_id' => $product['id'],
                    'product_name' => $product['product_name'],
                    'sku_name' => $product['shop_min_sku']['sku_name'],
                    'product_pic' => empty($product['detail_pic']) ? $product['main_pic'][0]['file_info']['url'] : $product['detail_pic'][0]['file_info']['url'],
                    'price' => floatval($product['shop_min_sku']['sku_min_price']),
                    'land_mark' => empty($product['landmark_info']) ? "" : $product['landmark_info']['name'],
                    'dc_name' => empty($product['center_info']) ? "" : $product['center_info']['name'],
                    'shop_type' => empty($product['shop_info']) ? "" : ($product['shop_info']['type'] == 3 ? "制造商" : "商家"),
                    'industry_id' => $product['industry_id']
                ];
                $return['industry_id'][$product['id']] = $product['industry_id'];
            }
            $return['moment_products'] = $data['moment_products'];
            $return['product_json'] = json_encode($tmp_products, 256);
        }
        $return['files_json'] = empty($tmp_files) ? "[]" : json_encode($tmp_files, 256);
        // 文章图片
        $return['article_images'] = $data['article_images'] ?? [];

        if (!empty($moments_id)) {
            $return['update_time'] = time();
        } else {
            $return['create_time'] = time();
        }
        return $return;
    }

    /**
     * 取消上架（回到草稿可编辑状态）
     * @param int $moments_id
     * @param int $user_id
     * @param bool $is_show 是否取消上架：true=上架 false=下架
     * @param bool|null $delete_act 下架类型（仅下架时有效）：false下架并编辑 true下架并删除
     * @return bool
     */
    public function isShowCheck(int $moments_id, int $user_id, bool $is_show, $delete_act): bool
    {
        $instance = $this->getModelInstance()->where('user_id', '=', $user_id)->find($moments_id);
        if (empty($instance)) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '记录不存在');
        }
        $instance->is_show = (int)$is_show;

        if (!isset($delete_act)) {
            // 上架并提交审核
            return $instance->save();
        } else {
            // 下架并删除
            if ($delete_act) {
                $instance->delete_time = time();
                $this->momentApply->deleteApply($moments_id);
                return $instance->save();
            }
        }
        return true;
    }

    /**
     * 申请或编辑申请
     * @param array $data
     * @param int $user_id
     * @param int $moment_from 1商家动态 2达人圈动态
     * @return int
     */
    public function applyMoments(array $data, int $user_id, int $moment_from = self::MOMENT_FROM_SHOP): int
    {
        /************************************** 保存动态 start ********************************/
        try {
            Db::beginTransaction();
            if (!empty($data['id'])) {
                $instance = $this->getModelInstance()->find($data['id']);
                // 编辑动态：获取实例（重新发布）
                if (empty($instance) || $instance->moments_style != $moment_from || empty($instance->toArray())) {
                    Db::rollBack();
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '动态不存在');
                }
                // 违规整改 - 待审核(申请单)
                $instance->check_status = self::STATUS_WAIT_CHECK;
                $data['act'] = 1;// 修改都为发布操作
            } else {
                // 新实例
                $instance = $this->getModelInstance();
            }

            //////////////////////////修改申请-修改即可见 -- start////////////////////////
            $filter_data = array_filter($data, function ($fields) {
                if (!in_array($fields, ['shop_id', 'user_id', 'type', 'video_file', 'create_time', 'update_time',
                    'issue_time', 'is_show', 'article_title', 'article', 'video_desc', 'topic_id', 'moments_style'])) {
                    return false;
                } else {
                    return true;
                }
            }, ARRAY_FILTER_USE_KEY);
            $filter_data['create_time'] = time();
            $filter_data['update_time'] = time();
            $filter_data['moments_style'] = $moment_from;
            foreach ($filter_data as $field => $val) {
                $instance->$field = $val;
            }
            $instance->user_id = $user_id;
            // 保存动态信息
            if (!$instance->save()) {
                Db::rollBack();
                return 0;
            }
            /************************************** 保存动态 END ***********************************/

            /************************* 保存关联商品或文章图片 start *******************/
            $profile_instance = make(MomentsProfile::class);
            $profile_p = [];
            if (!empty($data['moment_products'])) {
                foreach ($data['moment_products'] as $p_id) {
                    $profile_p[] = [
                        'moments_id' => $instance->id,
                        'file_type' => self::PROFILE_PRODUCT,
                        'fileinfo_id' => 0,
                        'product_id' => $p_id,
                        'industry_id' => $data['industry_id'][$p_id]
                    ];
                }
            }
            if (!empty($data['article_images'])) {
                foreach ($data['article_images'] as $img_id) {
                    $profile_p[] = [
                        'moments_id' => $instance->id,
                        'file_type' => self::PROFILE_ARTICLE_IMG,
                        'fileinfo_id' => $img_id,
                        'product_id' => 0,
                        'industry_id' => 0
                    ];
                }
            }
            // 删除关联的附件
            if (!empty($data['id'])) {
                $profile_instance->where(['moments_id' => $data['id']])->delete();// 删除原来动态绑定的附件
            }
            if (!empty($profile_p)) {
                $profile_instance->insert($profile_p);// 重新绑定动态附件
            }
            /******************** 保存关联商品或文章图片 end ***************************/
            //////////////////////////修改申请-修改即可见 -- end////////////////////////

            // 获取申请单信息
            $get_apply_data = $this->momentApply->getApplyData($data);
            // 取消发布并修改
            if (!empty($data['id'])) {
                $get_apply_data['apply_status'] = MomentsApplyService::STATUS_WAIT_CHECK;
            } else {
                // 首次发布
                if ($data['act'] == 1) {
                    $get_apply_data['apply_status'] = MomentsApplyService::STATUS_WAIT_CHECK;// 草稿
                } else {
                    // 创建并保存为草稿、未提交审核
                    $get_apply_data['apply_status'] = MomentsApplyService::STATUS_DRAFT;// 待审核
                }
            }
            $get_apply_data['moments_id'] = $instance->id;
            $get_apply_data['moments_style'] = $moment_from;
            // 申请单保存失败
            if (!$id = $this->momentApply->saveApply($get_apply_data)) {
                Db::rollBack();
                return 0;
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            throw new BusinessException(ErrorCode::NORMAL_ERROR, $exception->getMessage());
        }
        Db::commit();
        return $id;
    }

    /**
     * 获取动态详情（用户）
     * @param int $id
     * @param int $user_id
     * @return array
     */
    public function getMomentsInfo(int $id, int $user_id): array
    {
        $moments_instance = $this->getModelInstance()
            ->with(['with_img_profiles', 'with_sku_profiles', 'with_video_profiles', 'with_reviews', 'with_hearts', 'with_stars'])
            ->select(['id', 'article', 'article_title', 'issue_time', 'video_file', 'heart_num', 'review_num', 'star_num', 'video_desc'])
            ->find($id);
        if (empty($moments_instance) || empty($moments_instance->toArray())) {
            return [];
        }
        $arr = $moments_instance->toArray();
        $arr['i_give_heart'] = 0;
        $arr['i_give_stars'] = 0;
        // 文章是否已点赞
        foreach ($arr['with_hearts'] as $with_heart) {
            if ($with_heart['with_reviewer']['id'] == $user_id) {
                $arr['i_give_heart'] = 1;
            }
        }
        // 文章是否已收藏
        foreach ($arr['with_stars'] as $with_star) {
            if ($with_star['with_reviewer']['id'] == $user_id) {
                $arr['i_give_stars'] = 1;
            }
        }
        unset($arr['with_stars'], $arr['with_hearts']);
        foreach ($arr['with_reviews'] as $k => &$item) {
            $item['i_give_heart'] = 0;
            // 我点过赞的评论
            if (!empty($item['with_hearts'])) {
                foreach ($item['with_hearts'] as $with_heart) {
                    if ($with_heart['with_reviewer']['id'] == $user_id) {
                        $item['i_give_heart'] = 1;
                        break;
                    }
                }
                // 删除用户信息
                unset($item['with_hearts'], $item['with_reviewer']['id']);
            }
            // 我点过赞的评论回复
            if (!empty($item['with_sub_review'])) {
                foreach ($item['with_sub_review'] as &$sub_review) {
                    unset($sub_review['reviewer'], $sub_review['replay_user']);
                    $sub_review['i_give_heart'] = 0;
                    if (!empty($sub_review['with_hearts'])) {
                        foreach ($sub_review['with_hearts'] as $with_heart) {
                            if ($with_heart['with_reviewer']['id'] == $user_id) {
                                $sub_review['i_give_heart'] = 1;
                                break;
                            }
                        }
                    }
                    // 删除用户信息
                    unset($sub_review['with_hearts'], $sub_review['with_reviewer']['id'], $sub_review['with_replay_user']['id']);
                }
            }
            unset($item['reviewer'], $item['with_reviewer']['id']);
        }

        return $arr;
    }

    /**
     * 评论文章||回复评论
     * @param int $user_id
     * @return bool
     */
    public function review(int $user_id): bool
    {
        // 动态ID 评论ID（为0时评论文章） 评论内容 评论类型
        $data = $this->request->inputs(['moments_id', 'replay_to', 'review_info']);
        // 商家动态
        $instance = $this->getModelInstance()->where('status', '=', self::STATUS_CHECKED)->find($data['moments_id']);
        if (empty($data['moments_id']) || empty($data['review_info'])) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '评论失败!');
        }

        // 用户评论信息
        $data['replay_to'] = $data['replay_to'] ?? 0;// 为0表示评论的文章
        $data['is_author'] = $user_id == $instance->user_id ? 1 : 0;
        $data['shop_id'] = $instance->shop_id;
        $data['reviewer'] = $user_id;
        $data['replay_time'] = time();
        $data['review_type'] = empty($data['replay_to']) ? 1 : 2;// 没有回复人：评论为文章
        $data['reviewer_ip'] = $this->getRealIp();
        $data['locate_tag'] = Common::getLocateByIp($data['reviewer_ip']);// 根据IP定位城市

        if ($this->reviews->review($data)) {
            // 评论成功:商家动态评论数+1
            $instance->review_num = Db::raw('review_num+1');
            $instance->save();
        } else {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '评论失败');
        }
        return true;
    }

    /**
     * 获取客户端请求真实IP地址
     * @return string
     */
    public function getRealIp(): string
    {
        try {
            $request = ApplicationContext::getContainer()->get(RequestInterface::class);

            $headers = $request->getHeaders();
            if (isset($headers['x-forwarded-for'][0]) && !empty($headers['x-forwarded-for'][0])) {
                return $headers['x-forwarded-for'][0];
            } elseif (isset($headers['x-real-ip'][0]) && !empty($headers['x-real-ip'][0])) {
                return $headers['x-real-ip'][0];
            }
            $serverParams = $request->getServerParams();

            return $serverParams['remote_addr'] ?? '';

        } catch (NotFoundExceptionInterface $e) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '获取IP地址失败');
        } catch (ContainerExceptionInterface $e) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '获取IP地址失败2');
        }
    }

    /**
     * 用户点赞收藏
     * @param array $params
     * @return bool
     */
    public function userFavorAct(array $params): bool
    {
        // 用户  点赞3|收藏4 动态ID（点赞||收藏）  评论ID（只能点赞）
        if (empty($params['user_id']) || empty($params['favor_type']) || empty($params['moments_id'])) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '缺少参数');
        }
        $moments_instance = $this->getModelInstance()->where('status', '=', self::STATUS_CHECKED)->find($params['moments_id']);
        if (empty($moments_instance)) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '操作失败');
        }
        Db::beginTransaction();
        try {
            $is_author = $moments_instance->user_id == $params['user_id'] ? 1 : 0;
            $type = $this->reviews->userFavorAct($params['favor_type'], $params['moments_id'], $params['user_id'], $moments_instance->shop_id, $is_author, $params['review_id'] ?? 0);
            if (empty($type)) {
                Db::rollBack();
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '操作失败2');
            }
            // 动态评论操作（1：点赞收藏 2：取消点赞收藏）
            if (empty($params['review_id'])) {
                $opt = $type == 1 ? "+1" : "-1";
                $numField = [MomentsReviewService::TYPE_ZAN => 'heart_num', MomentsReviewService::TYPE_STAR => 'star_num'];
                $effect_rows = $this->getModelInstance()
                    ->where(['id' => $params['moments_id']])
                    ->where(function ($where) use ($type, $params, $numField) {
                        // 取消收藏点赞
                        if ($type == 2) {
                            $where->where($numField[$params['favor_type']], '>', 0);
                        }
                    })->update([$numField[$params['favor_type']] => Db::raw($numField[$params['favor_type']] . $opt)]);
                if (empty($effect_rows)) {
                    Db::rollBack();
                    return false;
                }
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            print_r($exception->getMessage());
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '操作异常');
        }
        Db::commit();
        return true;
    }

    /**
     * 删除评论
     * @param int $review_id
     * @param int $user_id
     * @return bool
     */
    public function reviewDelete(int $review_id, int $user_id): bool
    {
        $res = $this->getModelInstance()
            ->query(true)
            ->where(['user_id' => $user_id, 'id' => $review_id, 'delete_time' => 0])
            ->update(['delete_time' => time()]);
        return boolval($res);
    }

    /**
     * 获取商家动态列表 或 用户达人圈动态列表
     * @param int $shop_id
     * @param array $wheres
     * @param int $has_cert 是否完善认证信息
     * @param int $moment_from 1商家动态 2达人圈动态
     * @param int $user_id 用户ID
     * @return Builder
     */
    public function getMomentsList(int $shop_id, array $wheres, $has_cert = 1, $moment_from = self::MOMENT_FROM_SHOP, $user_id = 0): Builder
    {
        $order_by_field = $wheres['order_by'] ?? "";
        if (in_array($order_by_field, ['view_count', 'heart_num'])) {
            $order_by_way = 'desc';// 1降序 0不排 -1升序
        }

        // 未认证
        if ($has_cert == 0) {
            $build = $this->getModelInstance()
                ->where(['shop_id' => $shop_id, 'delete_time' => 0])
                ->where(function ($where) use ($wheres) {
                    if (!empty($wheres['key_word'])) {
                        $where->where('fly_moments.article', 'like', '%' . $wheres['keyword'] . '%')
                            ->orWhere('fly_moments.video_desc', 'like', '%' . $wheres['keyword'] . '%');
                    }
                })
                ->with(['with_video_profiles', 'with_img_profiles', 'with_sku_profiles', 'with_curr_applys']);
        } else {
            $build = $this->getModelInstance()
                ->where(['delete_time' => 0])
                ->where(function ($where) use ($shop_id, $moment_from, $user_id) {
                    if ($moment_from == self::MOMENT_FROM_SHOP) {
                        // 商家动态
                        $where->where('shop_id', '=', $shop_id)
                            ->where('moments_style', '=', 1);
                    } else {
                        // 达人动态
                        $where->where('user_id', '=', $user_id)
                            ->where('moments_style', '=', 2);
                    }
                })
                ->where(function ($where) use ($wheres, $shop_id) {
                    if (isset($wheres['status'])) {
                        if ($wheres['status'] == 2) {
                            // 违规: 违规状态并且、非待审核状态（需要去修改）
                            $where->where('is_illegal', '=', self::ILLEGAL)->where('check_status', '<>', self::STATUS_WAIT_CHECK);// 非待审核
                        } else {
                            // 审核中
                            if ($wheres['status'] == 4) {
                                // 审核中： 只有审核中一种状态
                                $where->where('check_status', '=', self::STATUS_WAIT_CHECK);// 待审核
                            } else {
                                // 不违规情况下
                                $where->where('is_illegal', '=', 0);
                                // 并且为审核同状态
                                $where->where('check_status', '=', 1);
                                if ($wheres['status'] == 1) {
                                    // 上架状态
                                    $where->where('is_show', '=', 1);
                                } else {
                                    // 下架状态
                                    $where->where('is_show', '=', 0);
                                }
                            }
                        }
                        $where->where('shop_id', '=', $shop_id);
                    }
                    if (!empty($wheres['key_word'])) {
                        $where->where('fly_moments.article', 'like', '%' . $wheres['key_word'] . '%')
                            ->orWhere('fly_moments.video_desc', 'like', '%' . $wheres['key_word'] . '%');
                    }
                })->with(['with_video_profiles', 'with_img_profiles', 'with_sku_profiles', 'with_curr_applys']);
        }

        if (!empty($order_by_way)) {
            $build->orderBy($order_by_field, $order_by_way);
        }
        return $build->orderBy('issue_time', 'desc');
    }

    /**
     * 获取状态统计 违规、审核中、上下架
     * @param int $shop_id
     * @param int $moment_from
     * @return array
     */
    public function getStateCount(int $shop_id, $moment_from = self::MOMENT_FROM_SHOP): array
    {
        // 上架
        $is_show_up = $this->getModelInstance()->where([
            'shop_id' => $shop_id,
            'is_show' => self::SHOW_UP,
            'is_illegal' => self::LEGAL,
            'check_status' => self::STATUS_CHECKED,
            'delete_time' => 0])->count();// 上架
        // 下架
        $is_show_down = $this->getModelInstance()->where([
            'shop_id' => $shop_id,
            'is_show' => self::SHOW_DOWN,
            'is_illegal' => self::LEGAL,
            'check_status' => self::STATUS_CHECKED,
            'delete_time' => 0])->count();// 下架
        // 违规
        $is_illegal = $this->getModelInstance()->where([
            'shop_id' => $shop_id,
            'is_illegal' => self::ILLEGAL,
            'delete_time' => 0])->where('check_status', '<>', self::STATUS_WAIT_CHECK)->count();// 违规
        // 待审核
        $wait_check = $this->getModelInstance()->where([
            'shop_id' => $shop_id,
            'check_status' => self::STATUS_WAIT_CHECK,
            'delete_time' => 0])
            ->count();//待审核
        return [
            'show_on_count' => $is_show_up ?: 0,
            'show_off_count' => $is_show_down ?: 0,
            'illegal_count' => $is_illegal ?: 0,
            'wait_check' => $wait_check ?? 0
        ];
    }
}